//
//  CELoginSetVC.m
//  digitalCurrency
//
//  Created by 默认账户 on 2019/4/3.
//  Copyright © 2019 XinHuoKeJi. All rights reserved.
//

#import "CELoginSetVC.h"
#import "CESettingsCell.h"
#import "MineNetManager.h"
#import "MSVerifyCell.h"
#import "CustomButton.h"

@interface CELoginSetVC ()

@property (nonatomic, copy) NSArray *ptitles;
@property (nonatomic, strong) UIButton *besureBtn;
@property (nonatomic, strong) UITextField *oldPassword;
@property (nonatomic, strong) UITextField *latestPassword;
@property (nonatomic, strong) UITextField *certainPassword;
@property (nonatomic, strong) UITextField *verificationCode;

@end

@implementation CELoginSetVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.viewTitle.text = LocalizationKey(@"Change login password");
    _ptitles = @[LocalizationKey(@"Please enter verification code"),LocalizationKey(@"Please enter old password"),LocalizationKey(@"Please enter new password"),LocalizationKey(@"Please enter new password again")];

    [self.view addSubview:self.tableView];
    self.tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 300);
    self.tableView.rowHeight = 65;
    [self.tableView registerClass:[CESettingsCell class] forCellReuseIdentifier:@"setcell"];
    [self.tableView registerClass:[MSVerifyCell class] forCellReuseIdentifier:@"verifyCell"];
    
    self.tableView.separatorColor = [UIColor whiteColor];

    [self.view addSubview:self.besureBtn];
//    [ToolUtil view:self.besureBtn gradineViewOne:self.besureBtn.bounds colorOne:[UIColor colorWithHEX:maincolor] colorTwo:[UIColor colorWithHEX:mainGradientColor]];

    
    @weakify(self);
    [[self.besureBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        [self submit];
    }];
    
}
- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,40,0,40)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,40,0,40)];
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _ptitles.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row) {
        CESettingsCell *cell = [CESettingsCell createTableView:tableView];
        cell.placeHolder = _ptitles[indexPath.row];
        
        switch (indexPath.row) {
            case 1:
                self.oldPassword = cell.textField;
                break;
            case 2:
                self.latestPassword = cell.textField;
                break;
            case 3:
                self.certainPassword = cell.textField;
                break;
            default:
                break;
        }
        
        return cell;
    }
    else {
        MSVerifyCell *cell    = [MSVerifyCell createTableView:tableView];
        self.verificationCode = cell.textField;
        
        [[cell.verifyBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [self getVerificationCodeBtnClick:cell.verifyBtn];
        }];
        
        return cell;
    }
}
    
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0,40,0,40)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0,40,0,40)];
    }
}

- (void)submit {
    NSString *latestPassword   = self.latestPassword.text;
    NSString *oldPassword      = self.oldPassword.text;
    NSString *certainPassword  = self.certainPassword.text;
    NSString *verificationCode = self.verificationCode.text;
    
    if ([NSString stringIsNull:oldPassword]) {
        [self.view makeToast:[[ChangeLanguage bundle] localizedStringForKey:@"inputNewLoginPassword" value:nil table:@"English"] duration:1.5 position:CSToastPositionCenter];
        return;
    }
    if ([NSString stringIsNull:latestPassword]) {
        [self.view makeToast:[[ChangeLanguage bundle] localizedStringForKey:@"inputNewLoginPassword" value:nil table:@"English"] duration:1.5 position:CSToastPositionCenter];
        return;
    }
    if ([NSString stringIsNull:certainPassword]) {
        [self.view makeToast:[[ChangeLanguage bundle] localizedStringForKey:@"inputCertainLoginPassword" value:nil table:@"English"] duration:1.5 position:CSToastPositionCenter];
        return;
    }
    if (![latestPassword isEqualToString:certainPassword]) {
        [self.view makeToast:[[ChangeLanguage bundle] localizedStringForKey:@"checkPassword" value:nil table:@"English"] duration:1.5 position:CSToastPositionCenter];
        return;
    }
    if ([NSString stringIsNull:verificationCode]) {
        [self.view makeToast:[[ChangeLanguage bundle] localizedStringForKey:@"inputCode" value:nil table:@"English"] duration:1.5 position:CSToastPositionCenter];
        return;
    }
    
    if (![ToolUtil matchPassword:latestPassword]) {
        [self.view makeToast:LocalizationKey(@"Enter a password combining 8-20 digits and letters") duration:1.5 position:CSToastPositionCenter];
        return;
    }
    
    [EasyShowLodingView showLodingText:[[ChangeLanguage bundle] localizedStringForKey:@"loading" value:nil table:@"English"]];
    [MineNetManager resetLoginPasswordForCode:verificationCode withOldPassword:oldPassword withLatestPassword:latestPassword CompleteHandle:^(id resPonseObj, int code) {
        [EasyShowLodingView hidenLoding];
        if (code) {
            if ([resPonseObj[@"code"] integerValue]==0) {
                //上传成功
                [self.view makeToast:resPonseObj[MESSAGE] duration:1.0 position:CSToastPositionCenter];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
            else if ([resPonseObj[@"code"] integerValue] == -1000001 ){
                [ShowLoGinVC showLoginVc:self withTipMessage:resPonseObj[MESSAGE]];
            }
            else {
                [self.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
            }
        }
        else {
            [self.view makeToast:LocalizationKey(@"noNetworkStatus") duration:1.5 position:CSToastPositionCenter];
        }
    }];
}

//MARK:--获取验证码的点击事件
- (void)getVerificationCodeBtnClick:(UIButton *)sender {
    [EasyShowLodingView showLodingText:LocalizationKey(@"loading")];
    [MineNetManager resetLoginPasswordCodeForCompleteHandle:^(id resPonseObj, int code) {
        [EasyShowLodingView hidenLoding];
        if (code) {
            NSInteger resCode = [resPonseObj[@"code"] integerValue];
            if (resCode == 0) {
                [self.view makeToast:[[ChangeLanguage bundle] localizedStringForKey:@"getMessageCodeTip" value:nil table:@"English"] duration:1.5 position:CSToastPositionCenter];
                __block int timeout=60; //倒计时时间
                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
                dispatch_source_set_event_handler(_timer, ^{
                    if(timeout<=0){ //倒计时结束，关闭
                        dispatch_source_cancel(_timer);
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [sender setTitle:[[ChangeLanguage bundle] localizedStringForKey:@"getVerifyCode" value:nil table:@"English"] forState:UIControlStateNormal];
                            sender.userInteractionEnabled = YES;
                        });
                    }else{
                        int seconds = timeout % 90;
                        NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [sender setTitle: [NSString stringWithFormat:@"%@s",strTime] forState:UIControlStateNormal];
                            sender.userInteractionEnabled = NO;
                        });
                        timeout--;
                    }
                });
                dispatch_resume(_timer);
                
            }
            else if (resCode == -1000001 ){
                [ShowLoGinVC showLoginVc:self withTipMessage:resPonseObj[MESSAGE]];
            }
            else {
                [self.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

- (UIButton *)besureBtn {
    if (!_besureBtn) {
        _besureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _besureBtn.layer.masksToBounds = YES;
        _besureBtn.layer.cornerRadius = 22.0;
        [_besureBtn setTitle:LocalizationKey(@"Confirm")forState:UIControlStateNormal];
        [_besureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _besureBtn.backgroundColor = [UIColor colorWithHEX:maincolor];
        _besureBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        _besureBtn.frame = CGRectMake(23, 320, SCREEN_WIDTH-46, 44);
    }
    
    return _besureBtn;
}

@end
